package com.bz.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bz.item.service.ItemCategoryService;
import com.bz.mapper.TbItemCatMapper;
import com.bz.pojo.TbItemCat;
import com.bz.utils.Builder;
import com.bz.vo.CatNodeVo;
import com.bz.vo.CatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ItemCategoryServiceImpl extends ServiceImpl<TbItemCatMapper, TbItemCat> implements ItemCategoryService {

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    /**
     * 根据分类id查询子分类
     * @param id
     * @return
     */
    @Override
    public List<TbItemCat> selectItemCategoryByParentId(Long id) {
        QueryWrapper<TbItemCat> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbItemCat::getParentId,id)
                        .eq(TbItemCat::getStatus,1);
        return this.baseMapper.selectList(wrapper);
    }

    /**
     * 查询首页商品分类
     * @return
     */
    @Override
    public CatVo selectItemCategoryAll() {
        QueryWrapper<TbItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbItemCat::getStatus,1);
        List<TbItemCat> itemCatList = tbItemCatMapper.selectList(queryWrapper);
        List<?> catNodeVoList = this._children(itemCatList, 0L);
        //return Builder.of(CatVo::new).with(CatVo::setData,catNodeVoList).build();
        CatVo catVo = new CatVo();
        catVo.setData(catNodeVoList);
        return catVo;
    }

    // 递归筛选 查询首页商品分类
    private List<?> _children(List<TbItemCat> itemCatList,Long parentId){
        List catNodeVoList = new ArrayList<>();
        int count = 0;
        if (itemCatList != null && itemCatList.size() > 0){
            for (TbItemCat itemCat : itemCatList){
                if (parentId.equals(itemCat.getParentId())){
                    CatNodeVo catNodeVo = new CatNodeVo();
                    catNodeVo.setN(itemCat.getName());
                    if (itemCat.getIsParent()){
                        catNodeVo.setI(_children(itemCatList,itemCat.getId()));
                        catNodeVoList.add(catNodeVo);
                        count++;
                        if (count == 18){
                            break;
                        }
                    }else{
                        catNodeVoList.add(itemCat.getName());
                    }
                }
            }
        }
        return catNodeVoList;
    }
}
